#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include "client_init.h"  // 包含头文件，使用其中的声明
#define PORT 8080
// 不要在这里重复定义Client结构体，应通过头文件引用

// 只保留函数实现，确保与头文件声明一致
Client* client_init(const char* server_ip, int port) {
    Client* client = malloc(sizeof(Client));
    if (!client) {
        perror("内存分配失败");
        return NULL;
    }

    client->socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (client->socket_fd < 0) {
        perror("socket 创建失败");
        free(client);
        return NULL;
    }

    memset(&client->server_addr, 0, sizeof(client->server_addr));
    client->server_addr.sin_family = AF_INET;
    client->server_addr.sin_port = htons(port);

    if (inet_pton(AF_INET, server_ip, &client->server_addr.sin_addr) <= 0) {
        perror("无效的服务器 IP 地址");
        close(client->socket_fd);
        free(client);
        return NULL;
    }

    printf("正在连接服务器 %s:%d...\n", server_ip, port);
    if (connect(client->socket_fd, (struct sockaddr*)&client->server_addr, sizeof(client->server_addr)) < 0) {
        perror("connection to server failed");
        close(client->socket_fd);
        free(client);
        return NULL;
    }

    printf("成功连接到服务器 %s:%d\n", server_ip, port);
    return client;
}

